package com.lin.guli.service.base.handler;

import com.lin.guli.service.base.result.R;
import com.lin.guli.service.base.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice   //异常处理组件类，处理异常后返回的数据会转为json响应
public class GlobalExceptionHandler {
    //每个ExceptionHandler注解标注的方法都是一个异常处理类，处理注解绑定的类型的异常
    @ExceptionHandler(value = Exception.class)
    public R exception(Exception e){ //形参用来接收出现的异常，必须和@ExceptionHandler注解指定的异常一样
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error();
    }
    //也可以根据具体异常类型编写异常处理器
    //除数为0的异常
    @ExceptionHandler(value = ArithmeticException.class)
    public R exception(ArithmeticException e){
        log.error(ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.DIVIDE_ZERO_ERROR);
    }

    //json格式异常
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public R exception(HttpMessageNotReadableException e){
        log.error(ExceptionUtils.getStackTrace(e));
        return R.setResult(ResultCodeEnum.JSON_PARSE_ERROR);
    }
}
